package com.xxtx.trade.jwt;

import io.jsonwebtoken.*;
import jodd.util.ThreadUtil;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

/**
 * @ClassName JwtTokenExtUtil
 * @Description TODO token超时的待增加
 * @Author Jay.Wang
 */
public class JwtTokenExtUtil {

    public static String generateToken(JWTExtInfo jwtInfo, int expire) {
        try {
            JwtBuilder builder = Jwts.builder()
                    .claim("userId", jwtInfo.getUserId())
                    .claim("userName", jwtInfo.getUserName())
                    .signWith(SignatureAlgorithm.HS256, getKeyInstance());
            if (expire > 0) {
                builder.setExpiration(DateTime.now().plusSeconds(expire).toDate());
            }

            String compactJws = builder.compact();
            return compactJws;
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("H9Ihg8htFQzixaWH111");
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    private static Jws<Claims> parserToken(String token) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        return claimsJws;
    }

    public static IJWTInfo getInfoFromToken(String token) {
        try {
            Jws<Claims> claimsJws = parserToken(token);
            Claims body = (Claims) claimsJws.getBody();
            return new JWTInfo(body.get("userName").toString(), body.get("userId").toString());
        } catch (ExpiredJwtException expiredJwtException) {
//            throw expiredJwtException;
            JWTInfo jwtInfo = new JWTInfo(true);
            return jwtInfo;
        } catch (Exception var3) {

            throw new RuntimeException(var3);
        }
    }

    public static void main(String[] args) throws Exception {
        JWTExtInfo jwt = new JWTExtInfo("李四", "张三", System.currentTimeMillis());
        String token = generateToken(jwt, -1); //永久不失效
        System.out.println("token："+token);
        ThreadUtil.sleep(1000);
        JWTExtInfo jwt1 = new JWTExtInfo("123", "123", System.currentTimeMillis());
        String token1 = generateToken(jwt1, -1); //永久不失效
        System.out.println("token1:"+token1);
        IJWTInfo info = JwtTokenExtUtil.getInfoFromToken(token);
        System.out.println(info.getUserName());
    }
}
